package com.itservice.uzalarm;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.

import java.util.Calendar;

import android.app.AlarmManager;  
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

/**
 * This is an example of implementing an application service that will run in
 * response to an alarm, allowing us to move long duration work out of an
 * intent receiver.
 * 
 * @see AlarmService
 * @see AlarmService_Alarm
 */
public class UzalarmService extends Service {

    public static final int ALARM_LOOP = 5;
	private boolean DEBUG = false;
	private SharedPreferences pref_Alarm;
	private SharedPreferences.Editor pref_Alarm_editor;
	private long Setting_cnt = 0;/* 設定されているAlarm数 */
	
    @Override
    public void onCreate() {
    	
        // Start up the thread running the service.  Note that we create a
        // separate thread because the service normally runs in the process's
        // main thread, which we don't want to block.
        Thread thr = new Thread(null, mTask, "UzalarmService");
        thr.start();
    }

    @Override
    public void onDestroy() {
        // Cancel the notification -- we use the same ID that we had used to start it
 
        // Tell the user we stopped.
        Toast.makeText(this, "UzAlarm Setting Complete!", Toast.LENGTH_SHORT).show();
    }

    /**
     * The function that runs in our worker thread
     */
    Runnable mTask = new Runnable() {
        public void run() {

        	String data_name_key = "";
        	Setting_cnt = 0;	/* 初期化 */
        	if(DEBUG)Log.v("uzalarm", "setRepeating_start");
 
        	/* 以前設定分すべて削除 */
        	wakeup_setting_clean();
        	
        	//マネージャーキーの取得
        	SharedPreferences manege_pref = getSharedPreferences(Utility.PREF_MANAGER_KEY,MODE_WORLD_WRITEABLE);
        	int on_off = manege_pref.getInt(Utility.ON_OFF_KEY, 0);
        	
        	//ONスイッチが立っているものだけ確認する。
        	for(int loop = 0;loop < ALARM_LOOP;loop++)
        	{
            	Log.v("uzalarm", "Loop List" + loop);
        		/*
        		 * 	public static final int SUNDAY = 0x00000001;
				 *	public static final int MONDAY = 0x00000002;
				 *	public static final int TUESDAY = 0x00000004;
				 *	public static final int WEDNESDAY = 0x00000008;
				 *	public static final int THURSDAY = 0x00000010;
				 *	public static final int FRIDAY = 0x00000020;
				 *	public static final int SATURDAY = 0x00000040;
        		 */
        		
        		/* 指定位置に値が入っている場合、アラーム設定を行う。*/
	        	if((on_off & (0x0001 << loop)) == (0x0001 << loop))
	        	{
	        		/* loop回数によって取得するKEYを変更する。 */
	        		switch(loop)
	        		{
	        		case 0:
	                	data_name_key = manege_pref.getString(Utility.DATA1_NAME_KEY, "");
	                	break;
	        		case 1:
	                	data_name_key = manege_pref.getString(Utility.DATA2_NAME_KEY, "");
	                	break;
	        		case 2:
	                	data_name_key = manege_pref.getString(Utility.DATA3_NAME_KEY, "");
	                	break;
	        		case 3:
	                	data_name_key = manege_pref.getString(Utility.DATA4_NAME_KEY, "");
	                	break;
	        		case 4:
	                	data_name_key = manege_pref.getString(Utility.DATA5_NAME_KEY, "");
	                	break;
	        		}

	        		if(DEBUG)Log.v("uzalarm", "data_name_key :" + data_name_key);
	            	//1Dataの取得
	            	SharedPreferences list_pref = getSharedPreferences(data_name_key,MODE_WORLD_WRITEABLE);

                	/* 1データ毎に設定(一週間分) */
                	wakeup_setting_weekly(list_pref);
	        	}
        	}

        	/* 設定したアラーム情報を別のSharedPreferencesへ設定する */
        	pref_Alarm = getSharedPreferences(Utility.ALARM_SETTING_KEY,Context.MODE_PRIVATE);
        	pref_Alarm_editor = pref_Alarm.edit();
        	pref_Alarm_editor.putLong(Utility.ALARM_SETTING_NUM, Setting_cnt);
        	/* コミット */
        	pref_Alarm_editor.commit();

        	// サービス終了
            UzalarmService.this.stopSelf();
            if(DEBUG)Log.v("log_shima", "--------------- > shima_Service_stop < ---------------");
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    /**
     * This is the object that receives interactions from clients.  See RemoteService
     * for a more complete example.
     */
    private final IBinder mBinder = new Binder() {
        @Override
		protected boolean onTransact(int code, Parcel data, Parcel reply,
		        int flags) throws RemoteException {
            return super.onTransact(code, data, reply, flags);
        }
    };
    
    /* 一週間分設定 */
    private int wakeup_setting_weekly(SharedPreferences pref)
    {
    	/* SharedPreferencesから一回分のデータ取得 */
    	int weekly_data 		= pref.getInt(Utility.WEEKLY_CONF_KEY, 0);
    	long ret = 0;
    	/* SharedPreferences */
    	pref_Alarm = getSharedPreferences(Utility.ALARM_SETTING_KEY,Context.MODE_PRIVATE);
    	pref_Alarm_editor = pref_Alarm.edit();
  	
    	if(DEBUG)Log.v("uzalarm", "wakeup_setting_weekly weekly_data" + weekly_data);

        /* 曜日毎に設定する */
        /* 1bit毎に日曜日から土曜日まで設定されているのでビットシフトしながら確認する */
        for(int loop = 0; loop < 7 ;loop++)
        {
        	/* ビットシフトさせながら該当の曜日をONするか確認する。 */
        	if((weekly_data & (1 << loop)) != 0)
        	{
        		/* アラームを設定する。loopは曜日情報として渡す。（カレンダー情報一致させるため+1している） */
            	ret = wakeup_setting_day(pref,(loop+1));
            	
            	if(DEBUG)Log.v("uzalarm", "Loop:" + loop + "Setting_cnt:" + "  " );

            	/* 設定したアラーム情報を別のSharedPreferencesへ設定する */
            	pref_Alarm_editor.putString(Long.toString(Setting_cnt), Long.toString(ret));
            	Setting_cnt++;
        	}
    	}

    	/* コミット */
    	pref_Alarm_editor.commit();
        return(0);
    }
    
    /* 一日分設定 */
    /* 曜日説明 1:日 2:月 3:火 4:水 5:木 6:金 7:土 */
    private long wakeup_setting_day(SharedPreferences pref,int youbi)
    {
    	String music_file_path  = pref.getString(Utility.FILEPATH_KEY, "");
    	int game_mode			= pref.getInt(Utility.GAME_CONF_KEY, 1);
    	int setHour				= pref.getInt(Utility.WAKE_HOUR_KEY, 0);
    	int setMin 				= pref.getInt(Utility.WAKE_MIN_KEY, 0);
    	
    	if(DEBUG)Log.v("uzalarm", "wakeup_setting_day" + youbi);
    	
    	/* カレンダー情報取得 */
        Calendar c = Calendar.getInstance();
        
        String w[] = {"SUN","MON","TUS","WED","THU","FRI","SAT"};
        /* 現在時間の取得 */
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
    	int preHour   = c.get(Calendar.HOUR_OF_DAY);
    	int preMin	  = c.get(Calendar.MINUTE);
   	
    	/* AlarmManager */
        Context context = UzalarmService.this;  
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);  
    	
    	/* 現在時刻から設定する日時を計算する */
        /* 曜日設定 */
        if(dayOfWeek < youbi)
        {
        	c.add(Calendar.DATE, youbi - dayOfWeek);
        }
        else if(dayOfWeek > youbi)
        {
        	c.add(Calendar.DATE, youbi - dayOfWeek + 7);
        }
        else
        {
        	/* 曜日が同じ場合は時間が今より早い時間であれば一週間後, */
        	/* 遅ければ当日鳴らす */
            if( preHour > setHour)
            {
            	c.add(Calendar.DATE, 7);
            }
            else if( preHour == setHour)
            {
            	/* Hourが同じならMinを見直す */
                if( preMin >= setMin)
                {
                	c.add(Calendar.DATE, 7);
                }
            }
        }
        /* 時間設定(時：分：秒)秒は0固定 */
        c.set(Calendar.HOUR_OF_DAY, setHour);
       	c.set(Calendar.MINUTE, setMin);
       	c.set(Calendar.SECOND, 0);

    	Log.v("uzalarm", "Set" + setHour +":" + setMin + w[c.get(Calendar.DAY_OF_WEEK) - 1]);
    	
       	
       	/* 設定後のミリ秒換算した時刻を取得 */
        long currentTimeMillis = c.getTimeInMillis();  
        if(DEBUG)currentTimeMillis = System.currentTimeMillis();
        
       	
        /* Intent作成 */
		//宛先をBroadcastへ変更
        Intent intent = new Intent(context, UzalarmReceiver.class);  
    	// ダミーのため設定時間を入れておくこれがないと複数個設定できない。 
    	intent.setType(Long.toString(currentTimeMillis));
    	Log.v("uzalarm", "!!!!!! mirisec" + Long.toString(currentTimeMillis));

    	intent.setAction(Utility.ALARM_ACTION);
        intent.putExtra("uzalarm_music_path", music_file_path);
        intent.putExtra("uzalarm_game_mode", game_mode);

        // PendingIntentの作成 
        PendingIntent pendingIntent = PendingIntent.getBroadcast(  
                context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);  

        // アラームの設定 
        alarmManager.set(AlarmManager.RTC, currentTimeMillis, pendingIntent);
        
        return(currentTimeMillis);
    }
    
    /* AlarmManagerに設定した全設定分削除 */
    private int wakeup_setting_clean()
    {
    	String Alarmtime;
    	int loop ;
    	/* 設定したアラーム情報を別のSharedPreferencesへ設定する */
    	pref_Alarm = getSharedPreferences(Utility.ALARM_SETTING_KEY,Context.MODE_PRIVATE);
    	pref_Alarm_editor = pref_Alarm.edit();

    	Setting_cnt = pref_Alarm.getLong(Utility.ALARM_SETTING_NUM, 0);
   	
    	if(DEBUG)Log.v("uzalarm", "wakeup_setting_clean_start cnt:" + Setting_cnt);
    	
    	for(loop = 0; loop < Setting_cnt; loop++)
    	{
	    	Alarmtime = pref_Alarm.getString( Integer.toString(loop), "");
	    	if(DEBUG)Log.v("uzalarm", "Alarmtime :" + loop + ":" + Alarmtime);
	    	/* AlarmManager起動 */
	    	Context context = UzalarmService.this;  
	        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);  
	        /* Intent作成 */
			//宛先をBroadcastへ変更
	        Intent intent = new Intent(context, UzalarmReceiver.class);  
	    	intent.setType(Alarmtime);
	    	intent.setAction(Utility.ALARM_ACTION);
	
	        // PendingIntentの作成 
	        PendingIntent pendingIntent = PendingIntent.getBroadcast(  
	                context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);  
	
	        // アラームのキャンセル
	        alarmManager.cancel(pendingIntent);
    	}

        //すべて消す
        pref_Alarm_editor.clear().commit();
        Setting_cnt = 0;
        return(0);
    }
}